import React, { Component } from 'react';
import { WhiteSpace, List, InputItem, Toast } from 'antd-mobile';
import { withRouter, Link } from 'react-router-dom';
import YwxNavBar from '../../components/common/YwxNavBar/YwxNavBar';
import YwxButton from '../../components/common/YwxButton/YwxButton';

class Task extends Component {

    constructor(props) {
        super(props);
        this.state = {
            name: '',
            phone: ''
        }
    }

    nameChange = (value) => {
        this.setState({
            name: value
        });
    }

    phoneChange = (value) => {
        this.setState({
            phone: value
        });
    }

    validate(callback) {
        let {
            name,
            phone
        } = this.state;
        phone = phone.replace(/\s/g, '');
        let msg = '';
        if (!name) {
            msg = '请输入姓名'
        } else if (!React.$utils.validatePhone(phone)) {
            msg = '请输入正确的手机号'
        }
        if (msg) {
            Toast.fail(msg)
        } else {
            callback && callback();
        }
    }

    onSubmit = () => {
        this.validate(() => {
            let {
                name,
                phone
            } = this.state;
            phone = phone.replace(/\s/g, '');
            React.$utils.request({
                url: '/app/userReport',
                method: 'post',
                data: {
                    userName: name,
                    phone
                }
            }).then(res => {
                Toast.success('报件成功');
                this.setState({
                    name: '',
                    phone: ''
                });
            })
        })
    }

    render() {
        return (
            <div className='task'>
                <YwxNavBar rightContent={<Link to='/task/log'>记录</Link>}>用户报件</YwxNavBar>
                <WhiteSpace />
                <List>
                    <InputItem placeholder='请填写用户的姓名' onChange={this.nameChange} value={this.state.name}>姓名</InputItem>
                    <InputItem placeholder='请填写用户的手机号' onChange={this.phoneChange} type='phone' value={this.state.phone}>手机号码</InputItem>
                </List>
                <YwxButton onClick={this.onSubmit}>开始报件</YwxButton>
            </div>
        );
    }
}

export default withRouter(Task);